﻿using CaptchaGen.NetCore;
using FYSJcrm.Core.Common;
using FYSJcrm.Core.IRepository.PermManage;
using FYSJcrm.Core.IRepository.SystemManage;
using FYSJcrm.Core.Model.SystemManage;
using FYSJcrm.Core.Web.Areas.AdminManage.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Web.Areas.AdminManage.Controllers
{
    [Area(nameof(AdminManage))]
    public class MainController : Controller
    {
        private readonly IManagerRepository _managerRepository;
        private readonly ISystemLogRepository _systemLogRepository;
        private readonly INavigationRepository _navigationRepository;
        private readonly ILogger<MainController> _logger;

        public MainController(IManagerRepository managerRepository,
            ISystemLogRepository systemLogRepository,
            INavigationRepository navigationRepository,
            ILogger<MainController> logger)
        {
            _managerRepository = managerRepository;
            _systemLogRepository = systemLogRepository;
            _navigationRepository = navigationRepository;
            _logger = logger;
        }

        public async Task<IActionResult> Index()
        {
            int? userId = HttpContext.Session.GetInt32("LoginUserId");

            if (userId == null)
            {
                return Redirect("~/AdminManage/Main/Login");
            }

            MainViewModel model = new MainViewModel
            {
                Manager = await _managerRepository.Select.Include(p => p.ManagerRole).Where(p => p.Id == userId).FirstAsync(),
                Navigations = await _navigationRepository.Select.OrderBy(p => p.SortId).ToTreeListAsync()
            };

            return View(model);
        }

        public IActionResult WelCome()
        {
            return View();
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model)
        {
            if (model.VerifyCode.ToUpper() != (string)TempData["verifyCode"])
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "验证码错误" });
            }

            var manager = await _managerRepository.Select.Where(p => p.UserName == model.UserName).FirstAsync();

            if (manager == null)
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "用户名或密码错误" });
            }

            if (manager.Password != DESEncrypt.Encrypt(model.Password, manager.Salt))
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "用户名或密码错误" });
            }

            HttpContext.Session.SetInt32("LoginUserId", manager.Id);

            SystemLogEntity systemLog = new SystemLogEntity
            {
                UserId = manager.Id,
                LoginIP = HttpContext.Connection.RemoteIpAddress.ToString(),
                Message = "后台登陆"
            };

            await _systemLogRepository.InsertAsync(systemLog);

            return Json(new AjaxResult { Code = HttpCode.OK, Data = "登陆成功" });
        }

        /// <summary>
        /// 创建验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CreateVerifyCode()
        {
            string verifyCode = Utils.GetCheckCode(4);
            TempData["verifyCode"] = verifyCode;
            MemoryStream ms = ValideCode(verifyCode);

            return File(ms, "image/jpeg");
        }

        /// <summary>
        /// 退出登陆
        /// </summary>
        /// <returns></returns>
        public IActionResult LoginOut()
        {
            HttpContext.Session.Clear();
            return Redirect("~/AdminManage/Main/Login");
        }

        private MemoryStream ValideCode(string code)
        {
            Bitmap Img = null;
            Graphics g = null;
            Random random = new Random();
            //验证码颜色集合  
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            //验证码字体集合  
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

            //定义图像的大小，生成图像的实例  
            Img = new Bitmap((int)code.Length * 18, 32);
            g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象    
            g.Clear(Color.White);//背景设为白色  

            //在随机位置画背景点  
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(Img.Width);
                int y = random.Next(Img.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }
            //验证码绘制在g中  
            for (int i = 0; i < code.Length; i++)
            {
                int cindex = random.Next(7);//随机颜色索引值  
                int findex = random.Next(5);//随机字体索引值  
                Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体  
                Brush b = new SolidBrush(c[cindex]);//颜色  
                int ii = 4;
                if ((i + 1) % 2 == 0)//控制验证码不在同一高度  
                {
                    ii = 2;
                }
                g.DrawString(code.Substring(i, 1), f, b, 5 + (i * 15), ii);//绘制一个验证字符  
            }
            MemoryStream ms = new MemoryStream();//生成内存流对象  
            Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中  
            ms.Seek(0, SeekOrigin.Begin);//指针回归

            //回收资源  
            g.Dispose();
            Img.Dispose();

            return ms;
        }
    }
}
